<template>
    <div id="mapContainer"></div>
    
  </template>
  
  <script lang="ts">
  import {
    defineComponent,
    ref,
    computed,
    reactive,
    onMounted,
    onUnmounted,
    toRefs,
  } from "vue";
  import MapInit from "@/components/mapContainer/mapInit.js";
  import popWindows from "@/components/popWindows/windows-1.vue";
  import popWindows2 from "@/components/popWindows/windows-2.vue";
  import { getCenter } from "@/components/_util/util";
import { contains } from "jquery";
  var polygon = null;
  export default defineComponent({
    components: {
      popWindows,
      popWindows2,
    },
    props: {
      data: Object,
      deviceArr: Array,
      inodeList:Array,
      inPoints:Array,
    },
    setup(props, { emit }) {
      let showFlag = ref(false);
      const state = reactive(props);
      const { data, deviceArr,inodeList, inPoints} = toRefs(state);
      const flag = ref(false);
      
      const propsData = reactive({
        areaData: {},
        pointData: {},
      });
      const etuokeJson = require("@/assets/json/etuokeqianBanner.json");
      const txtMenuItem = ref([
        {
          text: "放大",
          callback: function () {
            map.zoomIn();
          },
        },
        {
          text: "缩小",
          callback: function () {
            map.zoomOut();
          },
        },
        {
          text: "放置到最大级",
          callback: function () {
            map.setZoom(18);
          },
        },
        {
          text: "查看全国",
          callback: function () {
            map.setZoom(4);
          },
        },
        {
          text: "获得右键点击处坐标",
          isDisable: false,
          callback: function (lnglat) {
            console.log(lnglat.getLng() + "," + lnglat.getLat());
          },
        },
      ]);
  
      const pointArr = ref([
        {
          name: "一号摄像头",
          type: 1,
          lat: [107.51127, 38.20215],
        },
        {
          name: "二号摄像头",
          type: 1,
          lat: [107.52127, 38.21156],
        },
        {
          name: "一号虫情仪",
          type: 2,
          lat: [107.46711, 38.21759],
        },
        {
          name: "二号虫情仪",
          type: 2,
          lat: [107.47301, 38.21759],
        },
      ]);
      let map = null;
      let zoom = 14;
      let layL = null;
      let layT = null;
      let T = null;
      let infoWin1 = reactive(null);
      let allPolygon = reactive({
        value: [],
      });
      let allSet=reactive({
        value:[]
      })
      // 生命周期
      onMounted(() => {
        // init();
      });
      onUnmounted(() => {
        //
      });
  
      // methods
      function closeWindow() {
        //polygon.closeInfoWindow
  
        if (infoWin1) {
          map.removeOverLay(infoWin1);
          infoWin1 = null;
        }
      }
      //初始化地图
      const init = () => {
        MapInit.init().then((res) => {
          T = res;
          let imageURL =
            "http://t0.tianditu.gov.cn/img_w/wmts?" +
            "SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles" +
            "&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=729cb66926dcefcee8742ff04c4bf35a";
          let imageURT =
            "http://t0.tianditu.gov.cn/cia_w/wmts?" +
            "SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cia&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles" +
            "&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=729cb66926dcefcee8742ff04c4bf35a";
          //创建自定义图层对象
          layL = new T.TileLayer(imageURL, { minZoom: 5, maxZoom: 18 });
          layT = new T.TileLayer(imageURT, { minZoom: 5, maxZoom: 18 });
          let config = { layers: [layL, layT] };
          //初始化地图对象
          map = new T.Map("mapContainer", config);
          let LngLat = etuokeJson.features[0].properties.center;
          //设置显示地图的中心点和级别
          // map.centerAndZoom(new T.LngLat(108.406082, 37.701533), zoom);
          //允许鼠标滚轮缩放地图
          map.enableScrollWheelZoom();
          drawMap()
        //   drawLine();
        //   drawRoad();
        //   drawWaterRoad()
        //   addMenu();
         
        //   drawPolygon();
         
        //   drawSet()
        //   addLabel();
          showFlag.value = true;
        });
      };
      
      function drawSet(){
        allSet.value.forEach((item) => {
          map.removeOverLay(item)
        });
        deviceArr.value.forEach((item) => {
            drawPoint(item);
        });
      }
      function drawRoad() {
        let arr = [
          { lng: 107.450129, lat: 38.329085, name: "线路起点" },
          { lng: 107.449237, lat: 38.329633, name: "1号" },
          { lng: 107.448979, lat: 38.330063, name: "2号" },
          { lng: 107.446526, lat: 38.330072, name: "3号" },
          { lng: 107.445179, lat: 38.330676, name: "4号" },
          { lng: 107.44248, lat: 38.333605, name: "线路终点" },
        ];
        let points = [];
        arr.forEach((item) => {
          points.push(new T.LngLat(item.lng, item.lat));
        });
  
        let line = new T.Polyline(points, {
          weight: 6,
          //fillColor:'#F5DB31',
          color: "#F5DB31",
          opacity: 1,
          lineStyle: "dashed",
        });
        // //向地图上添加线
        map.addOverLay(line);
      }
      function drawWaterRoad() {
        return
        let lines = [
          [
            { lng: 107.44135, lat: 38.3353, name: "出水口1" },
            { lng: 107.44199, lat: 38.33442, name: "阀控器9" },
          ],
          [
            { lng: 107.44113, lat: 38.33408, name: "阀控器8" },
            { lng: 107.44199, lat: 38.33442, name: "阀控器9" },
            { lng: 107.44318, lat: 38.33488, name: "阀控器10" },
          ],
          [
            { lng: 107.44253, lat: 38.3337, name: "出水口2" },
            { lng: 107.443, lat: 38.33294, name: "阀控器5" },
          ],
          [
            { lng: 107.4423, lat: 38.33261, name: "阀控器6" },
            { lng: 107.443, lat: 38.33294, name: "阀控器5" },
            { lng: 107.44364, lat: 38.33322, name: "阀控器4" },
            { lng: 107.44418, lat: 38.33347, name: "阀控器3" },
            { lng: 107.4447, lat: 38.3337, name: "阀控器2" },
            { lng: 107.44515, lat: 38.3339, name: "阀控器1" },
          ],
          [
            { lng: 107.44364, lat: 38.33322, name: "阀控器4" },
            { lng: 107.44422, lat: 38.3324, name: "阀控器7" },
          ],
        ];
        lines.forEach((item) => {
          let points = item.map((item1) => {
            return new T.LngLat(item1.lng, item1.lat);
          });
          let line = new T.Polyline(points, {
          weight: 4,
          //fillColor:'#F5DB31',
          color: "#31C1F5",
          opacity: 1,
          lineStyle: "dashed",
        });
          //向地图上添加线
          map.addOverLay(line);
        });
      }
  
      function setMapCenter(arr) {
        let newArr = [];
        arr.forEach((item) => {
          newArr.push({
            lon: item[0],
            lat: item[1],
          });
        });
        let center = getCenter(newArr);
        
        map.centerAndZoom(new T.LngLat(center["lng"], center["lat"]), zoom);
      }
      function drawPolygon() {
        allPolygon.value.forEach((item) => {
          item.onRemove();
        });
       
        setMapCenter(data.value[0]["points"]);
        data.value.forEach((item) => {
        
          drawArea(item);
        });
      }
      const addLabel = () => {
        let latlng = new T.LngLat(107.48127, 38.18156);
        let addHtml = `<div class="dkdiv">
                        <div class='picicon'>
                        </div> 
                        <div class='rightt'>
                          <div class='name'>
                            地块组01
                          </div>
                          <div class='rightt2'>
                           
                              耕地面积:
                            
                            <div class='bold'>
                              25456
                            </div>  
                            亩
                          </div>
                        </div>
                    </div>`;
        let label = new T.Label({
          text: addHtml,
          position: latlng,
          offset: new T.Point(-9, 0),
        });
        //创建地图文本对象
        //map.addOverLay(label);
      };
      //添加右键菜单
      const addMenu = () => {
        let menu = new T.ContextMenu({ width: 140 });
        for (var i = 0; i < txtMenuItem.value.length; i++) {
          //添加菜单项
          var item = new T.MenuItem(
            txtMenuItem.value[i].text,
            txtMenuItem.value[i].callback
          );
          menu.addItem(item);
          if (i == 1 || i == 3) {
            //添加分割线
            menu.addSeparator();
          }
        }
        map.addContextMenu(menu);
      };
      //打点
      const drawPoint = (item) => {
        let icon = [
          require("../../assets/img/icon3.png"),
          require("../../assets/img/icon2.png"),
          require("../../assets/img/icon4.png"),
          require("../../assets/img/icon1.png"),
          require("../../assets/img/icon3.png"),
        ];
        // met:require("../../assets/img/icon3.png"),
        // mois:require("../../assets/img/icon2.png"),
        // water:require("../../assets/img/icon4.png"),
        // cam:require("../../assets/img/icon1.png"),
        // insect:require("../../assets/img/icon3.png")
        let name = ["气象设备", "墒情设备", "水肥机", "摄像头", "虫情设备"];
  
        let marker = new T.Marker(new T.LngLat(item.lat[0], item.lat[1]), {
          icon: new T.Icon({ iconUrl: icon[item.type - 1] }),
        });
       
        
        map.addOverLay(marker); //addOverLay方法，将覆盖物添加到地图中，一个覆盖物实例只能向地图中添加一次。
        marker.disableDragging(); //关闭标注拖拽功能,这里不关闭，标点就可以随便拖动
        allSet.value.push(marker)
      };
      function drawMap(){
        let getPlot=JSON.parse(sessionStorage.getItem('plotDetail'))
        
        let set=[]
        let set2=null
        if(getPlot.inodeList&&getPlot.inodeList.length>0){
            getPlot.inodeList.forEach(item=>{
                set.push([item.lng,item.lat])
            })
            setMapCenter(set)
        }
        if(getPlot.blockInodeList&&getPlot.blockInodeList.length>0){
            set2=JSON.stringify(getPlot.blockInodeList)
        }
        let getData={
            points:set,
            inPoints:set2
        }
        
        drawArea(getData)
        
      }
      //添加地图多边形覆盖
      const drawArea = (data) => {
        allPolygon.value.forEach(item=>{
          item.onRemove();
        })
        let points = [];
        data.points.forEach((item) => {
            
          points.push(new T.LngLat(item[0], item[1]));
        });
        console.log(12333333333,points)
        //创建面对象
        
        let polygon = new T.Polygon(points, {
          data: 'rgba(20, 204, 131, 1)',
          color: 'rgba(20, 204, 131, 1)',
          weight: 3,
          opacity: 1,
          fillColor: 'rgba(20, 204, 131, 0.40)',
          fillOpacity: 1,
        });
  
        //向地图上添加面
        
        if (data.inPoints) {
            console.log('ggggggggg',data.inPoints)
          let points = [];
          JSON.parse(data.inPoints).forEach((item) => {
            points.push(new T.LngLat(item["lng"], item["lat"]));
          });
          let polygonSc = new T.Polygon(points, {
            color: "red",
            weight: 1,
            opacity: 0.5,
            fillColor: "red",
            fillOpacity: 0.5,
          });
          map.addOverLay(polygonSc);
          allPolygon.value.push(polygonSc);
        }
        map.addOverLay(polygon);
        allPolygon.value.push(polygon);
      };
  
      //覆盖物点击事件
      const polygonClick = (e) => {
        console.log(e);
      };
  
      //行政区划描边
      const drawLine = () => {
        let lines = etuokeJson.features[0].geometry.coordinates;
        let points = [];
        let style = {
          color: "red",
          weight: 4,
          opacity: 1,
          lineStyle: "dashed",
          fillColor: "transprent",
          fillOpacity: 0,
        };
        lines.forEach((line) => {
          var point = new T.LngLat(line[0], line[1]);
          points.push(point);
        });
        var poly = new T.Polygon(points, style);
        map.addOverLay(poly);
      };
  
      return {
        drawMap,
        drawPolygon,
        showFlag,
        init,
        addLabel,
        drawArea,
        flag,
        propsData,
        closeWindow,
        pointArr,
        drawPoint,
        drawSet,
      };
    },
  });
  </script>
  
  <style lang="scss">
  @import "@/assets/scss/index.scss";
  .tdt-label {
    background: transparent;
    border: none;
    padding: 0;
  }
  .tdt-infowindow-scrolled {
    height: auto !important;
    border: none !important;
    width: 600px !important;
  }
  .dkdiv {
    display: flex;
    align-items: center;
    background: rgba(255, 255, 255, 0.08);
    backdrop-filter: blur(10px);
    border-radius: 5px;
    color: #fff;
    font-size: 14px;
    padding: 5px;
    .rightt2 {
      color: #ccc;
      font-size: 12px;
      display: flex;
      align-items: center;
    }
    .rightt {
    }
    .bold {
      font-size: 25px;
      font-weight: bold;
      color: #fff;
      margin: 0 5px;
    }
    .picicon {
      width: 48px;
      height: 48px;
      background: url("../../assets/img/dikuai.png");
      background-size: 100% 100%;
      margin-right: 10px;
    }
  }
  #mapContainer {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 10;
  }
  #mapContainer2 {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 10;
  }
  .tdt-infowindow-content-wrapper {
    // min-width: 320px;
    // min-height: 200px;
    background: rgba(0, 0, 0, 0.16);
    backdrop-filter: blur(10px);
    opacity: 1;
  
    border-radius: 10px;
    color: #333;
    box-shadow: 0 3px 14px rgba(0, 0, 0, 0.4);
  }
  .tdt-container a.tdt-infowindow-close-button {
    top: 5px;
    right: 5px;
    width: 24px;
    height: 24px;
    font: 24px/24px Tahoma, Verdana, sans-serif;
    color: #fff;
  }
  </style>
  